import api from '@/http/api'
import useUtils from "@/hooks/useUtils.js";

const utils = useUtils();
export default {
	namespaced: true,
	state: {
		token: '',
		userInfo: null
	},
	getters: {
		getToken: state => utils.getStoreGetters(state, 'token'),
		getUserInfo: state => utils.getStoreGetters(state, 'userInfo', true),
	},
	mutations: {
		SET_TOKEN (state, val) {
			state.token = val
			localStorage.setItem('token', state.token)
		},
		SET_USER_INFO (state, val) {
			state.userInfo = val
			localStorage.setItem('userInfo', JSON.stringify(state.userInfo))
		}
	},
	actions: {
		async apiGetUserInfo ({ commit }) {
			const res = await api.getUserInfo()
			if (!res.code) {
				commit('SET_USER_INFO', res.data)
			}
		},

		async loginByOpenid({ commit, dispatch }) {
			const openid = sessionStorage.getItem('openid')
			if (!openid) return
			const res = await api.openidLogin({ openid })
			if (!res.code) {
				commit('SET_TOKEN', res.data.token)
				await dispatch('apiGetUserInfo')
			}
		},
	}
}
